/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package data;

import base.UserPreferences;
import exception.RepositoryException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 *
 * @author tacio
 */
public class UserPreferencesRepositoryXml implements IUserPreferencesRepository {

    private SAXBuilder sb;
    private Document xmlDoc;
    private Element rootElement;

    public UserPreferencesRepositoryXml() throws RepositoryException {
        try {
            this.sb = new SAXBuilder();
            InputStream preferencesXml = UserPreferencesRepositoryXml.class.getResourceAsStream("/resources/Preferences.xml");
            this.xmlDoc = sb.build(preferencesXml);
            this.rootElement = xmlDoc.getRootElement();
        } catch (JDOMException ex) {
            throw new RepositoryException(ex.getMessage());
        } catch (IOException ex) {
            throw new RepositoryException(ex.getMessage());
        }
    }

    public UserPreferences getUserPreferences() throws RepositoryException {
        UserPreferences preferences = new UserPreferences();
        preferences.setTaskPoolerRepeatInterval(new Integer(rootElement.getChild("taskPooler").getAttributeValue("repeatInterval")));
        return preferences;
    }

    public void setUserPreferences(UserPreferences preferences) throws RepositoryException {
        String repeatInterval = preferences.getTaskPoolerRepeatInterval().toString();
        rootElement.getChild("taskPooler").setAttribute("repeatInterval", repeatInterval);
        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        try {
            URL preferencesXml = UserPreferencesRepositoryXml.class.getResource("/resources/Preferences.xml");
            URI preferencesXmlURI = preferencesXml.toURI();
            outputter.output(xmlDoc, new FileWriter(preferencesXmlURI.getPath() + preferencesXmlURI.getQuery()));                        
        } catch (URISyntaxException ex) {
            Logger.getLogger(UserPreferencesRepositoryXml.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(UserPreferencesRepositoryXml.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }

 
}
